package com.ruoyi.web;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.framework.web.service.MyTokenService;
import com.ruoyi.system.domain.BlogDetails;
import com.ruoyi.system.domain.Comment;
import com.ruoyi.system.service.IBlogDetailsService;
import com.ruoyi.system.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
public class CommentViewController extends BaseController {
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IBlogDetailsService blogDetailsService;
    @Autowired
    private MyTokenService myTokenService;
    @RequestMapping("/blogcomments")
    public List<Comment> blogcomments(@RequestParam("id") String id){
        //System.out.println("blog="+id);

        //System.out.println(commentService.selectCommentByBlogId(Long.valueOf(id)));
        return commentService.selectCommentByBlogId(Long.valueOf(id));

    }
    @RequestMapping("/postcomment")
    public AjaxResult postcomment(@RequestParam("token")String token,@RequestParam("id")String id,@RequestParam("comment")String comment){
        Comment comment1=new Comment();
       Date date = new Date(System.currentTimeMillis());
        comment1.setBlogId(Long.valueOf(id));
        BlogDetails blogDetails = new BlogDetails();
        blogDetails.setBlogId(Long.valueOf(id));
       Integer commentnum =  blogDetailsService.selectBlogDetailsByBlogId(Long.valueOf(id)).getBlogCommentsNum();
       blogDetails.setBlogCommentsNum(commentnum+1);
        comment1.setCommentContent(comment);
        comment1.setCommentDate(date);
        if(token.equals("notoken")){
            comment1.setUsrPost(token);
        }
        else {
            String loginrule = myTokenService.getloginrole(token);
            Long ruleid = myTokenService.getloginid(token);
            if (loginrule.equals("employeelogin")) {
                loginrule = "seekerlogin";
            }
            comment1.setUsrPost(loginrule);
            comment1.setUserId(ruleid);
        }
        AjaxResult re = toAjax(commentService.insertComment(comment1));
        if(re.isSuccess()){
            //更新commentnum
            blogDetailsService.updateBlogDetails(blogDetails);

        }
        return re;
    }
}
